package demo.dcs.aspect;

import java.util.List;

import demo.dcs.MertricListener;
import demo.java.lang.management.jvm.AppTraceConfig;
import demo.java.lang.management.vo.MetricSpan;
import org.aspectj.lang.reflect.CodeSignature;


/**
 * @author mandy.hu
 *
 */
public class AbstractXdcsAspectJ implements XdcsAspectJ, MertricListener {
	
    private long startTime;
    private long endTime;

	@Override
	public void beforeAspectJ(Object signature,Object instance,Object[] args) {
		this.startTime = System.currentTimeMillis();
	}

	@Override
	public void beforeAspectJ1(Object signature, Object instance, Object[] args, Object thisInstance) {
		this.startTime = System.currentTimeMillis();
	}
	@Override
	public void beforeAspectJ4Exception(Object signature, Object instance, Object[] args,Throwable throwable) {
	}

	@Override
	public void afterAspectJ(Object result, Object signature,Object instance,Object[] args,Throwable throwable){
		this.endTime = System.currentTimeMillis();
		
		
	}
    public long getExecuteTime(){
        if(startTime != 0 || endTime != 0){
            return endTime - startTime;
        }
        return 0;
    }

	public long getStartTime() {
		return startTime;
	}

	public void setStartTime(long startTime) {
		this.startTime = startTime;
	}

	public long getEndTime() {
		return endTime;
	}

	public void setEndTime(long endTime) {
		this.endTime = endTime;
	}
	
	public boolean mercurySwitch() {
		return AppTraceConfig.getLocalConfig().isXdcsSwitch();
	}
	
	boolean isExceptionAllowed(Throwable e,Object signature) {
		CodeSignature cs = (CodeSignature) signature;
		Class[] exceptionTypes = cs.getExceptionTypes();
		for (Class<?> exceptionType : exceptionTypes) {
			if (exceptionType.isInstance(e)) {
				return true;
			}
		}
		return false;
	}

	Throwable throwIfAllowed(Throwable e,Object signature) throws Throwable {
		if (isExceptionAllowed(e,signature)) {
			throw e;
		}else if (e instanceof RuntimeException) {
			throw e;
		}else {
			return e;
		}
	}

    public boolean isDestroyed() {
        return false;
    }

	@Override
	public List<MetricSpan> collectMetric() {

		// TODO Auto-generated method stub
		
		return null;
	}

	@Override
	public boolean isSame(MertricListener listener) {

		// TODO Auto-generated method stub
		
		return false;
	}

	@Override
	public boolean isSameSource(MertricListener listener) {

		// TODO Auto-generated method stub
		
		return false;
	}

	@Override
	public String getMertricListenerType() {

		// TODO Auto-generated method stub
		
		return null;
	}
	
    
}
